﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ComponentGIS.Class;
using ESRI.ArcGIS.Controls;

namespace ComponentGIS.View
{
    public partial class FormAttributeTable : Form
    {
        #region 字段属性
        IMapControl2 m_pMapControl;
        IFeatureLayer m_pFeaLyr;
        IEngineEditor m_pEditor;
        #endregion

        #region 构造函数
        public FormAttributeTable(IMapControl2 pMapControl, bool isSelectionSet = false)
        {
            InitializeComponent();
            m_pMapControl = pMapControl;
            m_pEditor = new EngineEditorClass();
            if (isSelectionSet)
            {
                //订阅事件
                lstbLayersName.SelectedIndexChanged += lsbLayersName_SelectedIndexChanged_SelSet;
                //触发事件
                lstbLayersName.DataSource = BasicClass.GetFeatureSelectionNameList(pMapControl.Map);
            }
            else
            {
                //注册事件
                lstbLayersName.SelectedIndexChanged += lsbLayersName_SelectedIndexChanged;
                //触发事件
                lstbLayersName.DataSource = BasicClass.GetFeatureLayerNameList(pMapControl.Map);
            }
        }

        public FormAttributeTable(IMapControl2 pMapControl, string sFeaLyrName)
        {
            InitializeComponent();
            m_pMapControl = pMapControl;
            m_pEditor = new EngineEditorClass();
            List<string> lyrNameList = BasicClass.GetFeatureLayerNameList(pMapControl.Map);
            int index = lyrNameList.FindIndex(str => str == sFeaLyrName);
            lstbLayersName.SelectedIndexChanged += lsbLayersName_SelectedIndexChanged;
            lstbLayersName.DataSource = lyrNameList;
            lstbLayersName.SelectedIndex = index;
        }
        #endregion

        #region 事件响应
        //填充图层属性表
        private void lsbLayersName_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateAttributeTable();
        }
        //填充图层选择集
        private void lsbLayersName_SelectedIndexChanged_SelSet(object sender, EventArgs e)
        {
            //1 获取图层
            string sLyrName = lstbLayersName.SelectedItem.ToString();
            m_pFeaLyr = BasicClass.GetFeatureLayer(m_pMapControl.Map, sLyrName);
            //2 获取选择集
            IFeatureSelection pFeaSel = (IFeatureSelection)m_pFeaLyr;
            ISelectionSet pSelSet = pFeaSel.SelectionSet;
            IEnumIDs pIDs = pSelSet.IDs;
            //3 获取游标
            ICursor pCur;
            pSelSet.Search(null, false, out pCur);
            IFeatureCursor pFeaCur = (IFeatureCursor)pCur;
            //4 获取数据表
            DataTable dataTable = BasicClass.GetAttributeTable(pFeaCur);
            //5 绑定控件
            dgvAttributeTable.DataSource = dataTable;
            SetDgvColsSortMode(DataGridViewColumnSortMode.NotSortable);
            //6 状态栏
            lblCount.Text = "要素共：" + dataTable.Rows.Count.ToString();
        }
        //要素定位
        private void dgwAttributeTable_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                m_pMapControl.Map.ClearSelection();
                //选中要素
                IFeatureLayer pFeaLyr = m_pMapControl.get_Layer(lstbLayersName.SelectedIndex) as IFeatureLayer;
                IFeature pFeaSelected = pFeaLyr.FeatureClass.GetFeature(dgvAttributeTable.CurrentRow.Index);
                m_pMapControl.Map.SelectFeature(pFeaLyr, pFeaSelected);
                IActiveView pActiveView = m_pMapControl as IActiveView;
                pActiveView.Refresh();
                //定位
                if (pFeaSelected.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                {
                    ITopologicalOperator pTopo_Buffer = pFeaSelected.Shape as ITopologicalOperator;
                    IGeometry pGeo = pTopo_Buffer.Buffer(0.5);
                    IEnvelope pEnv = pGeo.Envelope;
                    pActiveView.Extent = pEnv;
                }
                else
                    pActiveView.Extent = pFeaSelected.Extent;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //要素选中
        private void dgvAttributeTable_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            dgvAttributeTable.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
            dgvAttributeTable.MultiSelect = true;
            dgvAttributeTable.Rows[e.RowIndex].Selected = true;
            if (e.Button == MouseButtons.Right)
            {
                //编辑状态
                if (m_pEditor.EditState == esriEngineEditState.esriEngineStateEditing)
                    rMenuItemDelFeaSel.Enabled = true;
                else
                    rMenuItemDelFeaSel.Enabled = false;
                rightMenuRow.Show(Control.MousePosition);
            }
        }
        //字段选中
        private void dgwAttributeTable_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            dgvAttributeTable.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
            dgvAttributeTable.MultiSelect = false;
            dgvAttributeTable.Columns[e.ColumnIndex].Selected = true;
            if (e.Button == MouseButtons.Right)
            {
                //编辑状态
                if (m_pEditor.EditState == esriEngineEditState.esriEngineStateEditing)
                    rMenuItemDelFields.Enabled = false;
                else
                    rMenuItemDelFields.Enabled = true;
                rightMenuCol.Show(Control.MousePosition);
            }
        }
        //要素选择
        private void dgwAttributeTable_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvAttributeTable.SelectedRows.Count > 0)
            {
                List<string> list = GetSelectionObjID();
                for (int i = 0; i < list.Count; i++)
                {
                    if (i == 0)
                        BasicClass.SelectFeatures(m_pFeaLyr, esriSelectionResultEnum.esriSelectionResultNew,
                            "OBJECTID = " + list[i], m_pMapControl.ActiveView);
                    else
                        BasicClass.SelectFeatures(m_pFeaLyr, esriSelectionResultEnum.esriSelectionResultAdd,
                        "OBJECTID = " + list[i], m_pMapControl.ActiveView);
                }
            }
        }
        //清空图层选择（工具条）
        private void toolBarBtnClearSel_Click(object sender, EventArgs e)
        {
            IFeatureSelection pFeaSel = (IFeatureSelection)m_pFeaLyr;
            pFeaSel.Clear();
            m_pMapControl.Refresh();
        }
        //定位图层选择（工具条）
        private void toolBarBtnZoomToSel_Click(object sender, EventArgs e)
        {
            IFeatureSelection pFeaSel = (IFeatureSelection)m_pFeaLyr;
            IGeometry pGeo = BasicClass.GetGeoUnion(pFeaSel);
            m_pMapControl.Extent = pGeo.Envelope;
            m_pMapControl.Refresh();
        }
        //删除选中要素（右键菜单）
        private void rMenuItemDelFeaSel_Click(object sender, EventArgs e)
        {
            if (dgvAttributeTable.SelectedRows.Count > 0)
            {
                List<string> list = GetSelectionObjID();
                for (int i = 0; i < list.Count; i++)
                {
                    //地图移除
                    IFeature pFea = m_pFeaLyr.FeatureClass.GetFeature(int.Parse(list[i]));
                    pFea.Delete();
                    pFea.Store();
                }
                m_pMapControl.Refresh();
                UpdateAttributeTable();
            }
        }
        //定位图层选择（右键菜单）
        private void rMenuItemZoomToFeaSel_Click(object sender, EventArgs e)
        {
            IFeatureSelection pFeaSel = (IFeatureSelection)m_pFeaLyr;
            IGeometry pGeo = BasicClass.GetGeoUnion(pFeaSel);
            m_pMapControl.Extent = pGeo.Envelope;
            m_pMapControl.Refresh();
        }
        //删除字段（右键菜单）
        private void rMenuItemDelFields_Click(object sender, EventArgs e)
        {
            IFields pFields = m_pFeaLyr.FeatureClass.Fields;
            DialogResult result = MessageBox.Show("是否删除选中要素？(删除后无法撤销)", "提示",
                  MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                int index = dgvAttributeTable.SelectedColumns[0].Index;
                IField pField = m_pFeaLyr.FeatureClass.Fields.Field[index];
                m_pFeaLyr.FeatureClass.DeleteField(pField);
                dgvAttributeTable.Columns.RemoveAt(index);
            }
        }
        #endregion

        #region 方法成员
        private List<string> GetSelectionObjID()
        {
            List<string> list = new List<string>();
            for (int i = 0; i < dgvAttributeTable.RowCount; i++)
            {
                if (dgvAttributeTable.Rows[i].Selected == true)
                    list.Add(dgvAttributeTable.Rows[i].Cells[0].Value.ToString());
            }
            return list;
        }

        private void SetDgvColsSortMode(DataGridViewColumnSortMode colSortMode)
        {
            for (int i = 0; i < dgvAttributeTable.ColumnCount; i++)
                dgvAttributeTable.Columns[i].SortMode = colSortMode;
        }

        private void UpdateAttributeTable()
        {
            //1 获取图层
            string sLyrName = lstbLayersName.SelectedItem.ToString();
            m_pFeaLyr = BasicClass.GetFeatureLayer(m_pMapControl.Map, sLyrName);
            //2 获取游标
            IFeatureCursor pFeaCur = m_pFeaLyr.Search(null, false);
            //3 获取数据表
            DataTable dataTable = BasicClass.GetAttributeTable(pFeaCur);
            //5 绑定控件
            dgvAttributeTable.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
            dgvAttributeTable.DataSource = dataTable;
            SetDgvColsSortMode(DataGridViewColumnSortMode.NotSortable);
            //6 状态栏
            lblCount.Text = "要素共：" + dataTable.Rows.Count.ToString();
        }
        #endregion

        private void toolBarBtnAddField_Click(object sender, EventArgs e)
        {
            FormAddField frm = new FormAddField(m_pFeaLyr);
            DialogResult result = frm.ShowDialog();
            //更新属性表
            if (result == DialogResult.OK)
                UpdateAttributeTable();
        }
    }
}
